﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Text;

namespace G.Net
{
    public class HttpPost : HttpRequest
    {
        /// <summary>
        /// Initializes a new instance of <see cref="HttpPost"/> with the specified <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The uri to identify a resource in the remote server.</param>
        public HttpPost(string uri)
            : base(uri)
        {
            base.Method = HttpMethod.Post;
            base.ContentType = "application/x-www-form-urlencoded";
        }

        /// <summary>
        /// Initializes a new instance of <see cref="HttpPost"/> with the specified <paramref name="uri"/> and <paramref name="postData"/>.
        /// </summary>
        /// <param name="uri">The uri to identify a resource in the remote server.</param>
        /// <param name="postData">The data to be posted.</param>
        public HttpPost(string uri, string postData)
            : this(uri)
        {
            this.PostData = postData;
        }

        /// <summary>
        /// Gets or sets the data to post (in url-encoded format).
        /// </summary>
        public virtual string PostData
        {
            get;
            set;
        }

        /// <summary>
        /// When overridden in derived classes, writes post data into the request stream.
        /// </summary>
        /// <remarks>
        /// ASCII encoding is used to convert <see cref="PostData"/> into bytes. 
        /// Other encoding like UTF8 could cause unexpected issue in some cases like AddToFavorite.
        /// </remarks>
        /// <param name="reqStream">The request stream to write data with.</param>
        protected override System.Net.Http.HttpContent WriteBody()
        {
            if (!string.IsNullOrEmpty(PostData))
            {
                return new System.Net.Http.StringContent(PostData);
            }
            else
                return null;
        }

        protected override void AppendHeaders(System.Net.Http.Headers.HttpRequestHeaders headers)
        {
            base.AppendHeaders(headers);
            headers.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("utf-8"));
        }
    }
}
